package com.hunktimes.wholesale.util

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import com.hunktimes.wholesale.App
import java.io.File

/**
 * Author: Delete
 * Date: 2019/7/22 15:18
 * Description:
 *
 */
object VersionUtil {
    fun getVersionName(): String {
        val packageManager = App.get().applicationContext.packageManager
        val packInfo =
            packageManager.getPackageInfo(
                App.get().applicationContext.packageName,
                0
            )
        return packInfo.versionName
    }

    @Suppress("DEPRECATION")
    fun getVersionCode(): Int {
        val packageManager = App.get().applicationContext.packageManager
        val packInfo =
            packageManager.getPackageInfo(
                App.get().applicationContext.packageName,
                0
            )
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
            packInfo.longVersionCode.toInt()
        else
            packInfo.versionCode
    }

    /**
     * @return true -> 需要显示升级 false -> 不需要显示升级
     */
    fun compareVersion(remoteVersion: Int, localVersion: Int) = remoteVersion > localVersion

    fun getAppName(): String {
        val packageManager = App.get().applicationContext.packageManager
        val packInfo =
//            packageManager.getPackageArchiveInfo(//可以用来测试 下载失败 重试
            packageManager.getPackageInfo(
                App.get().applicationContext.packageName,
                0
            )
        val labelRes = packInfo.applicationInfo.labelRes
        return App.get().applicationContext.resources.getString(labelRes)
    }


    /**
     * 安装apk
     */
    fun installApk(mContext: Context, file: File) {

        val intent = Intent(Intent.ACTION_VIEW)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK// 防止打不开应用
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            val contentUri =
                FileProvider.getUriForFile(mContext, "com.hunktimes.wholesale.fileProvider", file)
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive")
        }
        mContext.startActivity(intent)

    }
}